package com.egg.eggdemo;

import redis.clients.jedis.Jedis;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

// (2)并发版 - 使用线程模拟真实场景
public class EggBreakMultipleTest {
    public static void main(String[] args) throws InterruptedException {
        // 先初始化服务
        EggBreakService service = new EggBreakService();
        String[] userId = {"Alice", "Bob", "Charlie", "David", "Eve"};
//
//        // 模拟3天活动
//        for (int day = 1; day <= 3; day++) {
//            System.out.println("\n===== 第" + day + "天 =====");
//
//            // 使用线程池并发执行所有用户砸蛋
//            ExecutorService executor = Executors.newFixedThreadPool(userId.length);
//            // 为每个用户创建任务
//            for (String user : userId) {
//                executor.execute(() -> {
//                    String result = service.breakEgg(user);
//                    System.out.println(user + " 结果: " + result);
//                });
//            }
//
//            // 等待所有任务完成
//            executor.shutdown();
//            executor.awaitTermination(1, TimeUnit.SECONDS);
//
//            // 每天结束后重置（最后一天不重置）
//            if (day < 3) {
//                System.out.println("\n--- 每日重置 ---");
//                service.dailyReset();
//            }
//        }


        // 并发执行所有用户砸蛋
//        ExecutorService executor = Executors.newFixedThreadPool(userId.length);

        // 修改：增加并发数和重试次数
        int concurrentUsers = 5;
        int retriesPerUser = 2;

        CountDownLatch latch = new CountDownLatch(concurrentUsers * retriesPerUser);
        ExecutorService executor = Executors.newFixedThreadPool(concurrentUsers);

        for (String userid : userId) {
            // 第一次尝试
            executor.execute(() -> {
                try {
                    String result = service.breakEgg(userid);
                    System.out.println(userid + "第一次砸蛋: " + result);
                } finally { latch.countDown();
                }
            });

            // 第二次尝试
            executor.execute(() -> {
                try {
                    String result = service.breakEgg(userid);
                    System.out.println(userid + "同一天再试: " + result);
                } finally {
                    latch.countDown();
                }
            });
        }
        // 等待所有操作完成
        latch.await();
        executor.shutdown();
        executor.awaitTermination(5, TimeUnit.SECONDS);





        // 查看最终结果--Redis中的数据
        try (Jedis jedis = new Jedis("localhost", 6379)) {
            System.out.println("\n=== 最终状态 ===");
            for (String user : userId) {
                Map<String, String> userRecord = jedis.hgetAll("egg_break:user:" + user);
                System.out.println(user + "的记录: " + userRecord);
            }
            System.out.println("剩余奖券: " + jedis.hgetAll("egg_break:coupons"));
            System.out.println("当前天数: " + jedis.get("egg_break:current_day"));
        }

        service.dailyReset();  // 最后 更新活动天数和奖券数量

        service.close();
    }
}
